//
//  JSMessageInputView.m
//
//  Created by Jesse Squires on 2/12/13.
//  Copyright (c) 2013 Hexed Bits. All rights reserved.
//
//  http://www.hexedbits.com
//
//
//  Largely based on work by Sam Soffes
//  https://github.com/soffes
//
//  SSMessagesViewController
//  https://github.com/soffes/ssmessagesviewcontroller
//
//
//  The MIT License
//  Copyright (c) 2013 Jesse Squires
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
//  associated documentation files (the "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
//  following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
//  LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
//  OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import "JSMessageInputView.h"
#import "NSString+JSMessagesView.h"
#import "UIImage+JSMessagesView.h"
#import "UIColor+JSMessagesView.h"
#import "BanBu_SendMsg.h"
#import "BanBuAPIs.h"

#define SEND_BUTTON_WIDTH 78.0f

static id<JSMessageInputViewDelegate> __delegate;

@interface JSMessageInputView ()

- (void)setup:(CGRect)frame;
- (void)setupTextView:(CGRect)frame;

@end



@implementation JSMessageInputView


#pragma mark - Initialization
- (id)initWithFrame:(CGRect)frame snapMode:(BOOL)mode delegate:(id<UITextViewDelegate, JSMessageInputViewDelegate>)delegate
{
    self = [super initWithFrame:frame];
    if(self) {
        __delegate = delegate;
        _max = mode;
        [self setup:frame];
        self.textView.delegate = delegate;
    }
    return self;
}

+ (JSInputBarStyle)inputBarStyle
{
    if ([__delegate respondsToSelector:@selector(inputBarStyle)])
        return [__delegate inputBarStyle];
    
    return JSInputBarStyleDefault;
}

+(JSInputFieldStyle)inputFieldStyle
{
    if ([__delegate respondsToSelector:@selector(inputFieldStyle)])
    {
        return [__delegate inputFieldStyle];
    }
    return JSInputFieldStyleGrey;
}

- (void)dealloc
{
    self.textView = nil;
}

- (BOOL)resignFirstResponder
{
    [self.textView resignFirstResponder];
    return [super resignFirstResponder];
}

#pragma mark - Setup
- (void)setup:(CGRect)frame
{
    CGRect aframe = frame;
    aframe.size.width = aframe.size.width-10;
    self.aFrame = aframe;
    
//    self.image = [UIImage inputBar];
    self.backgroundColor = [UIColor whiteColor];
    self.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);
    self.opaque = YES;
    self.userInteractionEnabled = YES;
    [self setupTextView:frame];
}

- (void)setupTextView:(CGRect)frame
{
    self.textView = [[JSMessageTextView  alloc] initWithFrame:CGRectMake(17.5, 2,frame.size.width-30, frame.size.height)];
    self.textView.autoresizingMask = (UIViewAutoresizingFlexibleWidth  | UIViewAutoresizingFlexibleHeight);
    self.textView.backgroundColor = [UIColor clearColor];

    if (IS_IOS_7)
    {
        [self.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -10)];
    }
    else
    {
        [self.textView setContentInset:UIEdgeInsetsMake(-2, 4, 0, -6)];
    }

    self.textView.userInteractionEnabled = YES;
    [self addSubview:self.textView];
    
    UIImageView *inputFieldBack = [[UIImageView alloc] initWithFrame:CGRectMake(self.textView.frame.origin.x - 1.0f-19.5,
                                                                                -1,
                                                                                self.textView.frame.size.width + 2.0f+34,
                                                                                self.frame.size.height+2)];
    inputFieldBack.image = [UIImage inputField];
    inputFieldBack.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    inputFieldBack.backgroundColor = [UIColor clearColor];
    
    self.inputFieldBack = inputFieldBack;
    
    [self addSubview:inputFieldBack];
    [self initCustSlider:frame];
    [self bringSubviewToFront:self.textView];
}

-(void)initCustSlider:(CGRect)frame
{
    UIView * contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    contentView.backgroundColor = [UIColor clearColor];
    contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

    
    //右边图片
    self.backImage1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0.6, frame.size.width, frame.size.height-2.6)];
    UIImage *image1 = [UIImage imageNamed:@"clearBack.png"];
    self.backImage1.image = image1;
    
    self.backImage1.userInteractionEnabled = NO;
    self.backImage1.layer.cornerRadius = 4;
    [contentView addSubview:self.backImage1];
    
    //左边图片
    self.backImage2 = [[UIImageView alloc]initWithFrame:CGRectMake(1, 1, 0, frame.size.height-2.6)];
    self.backImage2.image = [UIImage imageNamed:@"volumeCell2.png"];
    self.backImage2.userInteractionEnabled = NO;
    [contentView addSubview:self.backImage2];
    
    //中间可拖拽、可移动图片
    self.buttonImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 1, 20, frame.size.height-2.6)];
    self.buttonImage.image = [UIImage imageNamed:@"slider_grey.png"];
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGesture:)];
    [self.buttonImage addGestureRecognizer:pan];
    self.buttonImage.userInteractionEnabled = YES;
    [contentView addSubview:self.buttonImage];
    
    [self addSubview:contentView];
    
    if (self.max)
    {
        [self setCustSlider:0];
    }
}

//平移手势
-(void)panGesture:(UIPanGestureRecognizer *)pan
{
    CGPoint point = [pan translationInView:self];
    
    if (point.x == point.y && point.x == 0)
    {
        return;
    }
    
    //计算本次偏移
    CGAffineTransform transform = CGAffineTransformMakeTranslation(point.x,0);
    if (self.trans.tx)
    {
        transform = CGAffineTransformConcat(transform, self.trans);
    }
    
    [self.buttonImage setTransform:transform];
    
    //防止拖过界，
    if (self.buttonImage.frame.origin.x>self.aFrame.size.width-10)
    {
        CGRect frame = self.buttonImage.frame;
        frame.origin.x = self.aFrame.size.width-10;
        frame.size.height = self.frame.size.height - 2.6;
        self.buttonImage.frame = frame;
        
        frame = self.backImage2.frame;
        frame.origin.x = 0;
        frame.size.width = self.aFrame.size.width;
        frame.size.height = self.frame.size.height - 2.6;
        self.backImage2.frame = frame;
    }
    else if (self.buttonImage.frame.origin.x<0)
    {
        CGRect frame = self.buttonImage.frame;
        frame.origin.x = 0;
        frame.size.height = self.frame.size.height - 2.6;
        self.buttonImage.frame = frame;
        
        frame = self.backImage1.frame;
        frame.origin.x = 0;
        frame.size.width = self.aFrame.size.width+10;
        frame.size.height = self.frame.size.height - 2.6;
        self.backImage1.frame = frame;
    }
    else
    {
        //设置左右图片的frame
        point = self.buttonImage.frame.origin;
        
        self.backImage2.frame = CGRectMake(0, 1, point.x, self.frame.size.height-2.4);
        self.backImage1.frame = CGRectMake(point.x+10-5, 0.6, self.aFrame.size.width-point.x+5, self.frame.size.height-2.6);
    }
    
    //拖动后事件
    if (pan.state == UIGestureRecognizerStateEnded)
    {
        self.trans = transform;
        [self setBack2];
    }
    self.buttonImage.userInteractionEnabled = YES;
}

//设置左右图片的偏移
-(void)setBack2
{
    if (self.previousValue>self.buttonImage.frame.origin.x)
    {
        self.max = NO;
    }
    else if(self.previousValue < self.buttonImage.frame.origin.x)
    {
        self.max = YES;
    }
    self.previousValue = self.buttonImage.frame.origin.x;
    
    //设置左右图片
    [self setCustSlider:0.5f];
}

//设置最后状态时的左右图片和“按钮”图片
-(void)setCustSlider:(CGFloat)time
{
        [UIView animateWithDuration:time
                     animations:^{
                         if (self.max)//在最右边显示
                         {
                             self.previousValue = self.aFrame.size.width;
                             
                             CGRect frame = self.buttonImage.frame;
                             frame.origin.x = self.aFrame.size.width-10+0.3;
                             frame.origin.y = 0.8;
                             frame.size.height = self.frame.size.height-2.7;
                             self.buttonImage.frame = frame;
                             
                             frame = self.backImage2.frame;
                             frame.size.width = self.aFrame.size.width;
                             frame.size.height = self.frame.size.height-2.6;
                             self.backImage2.frame = frame;
                         }
                         else//在最左边显示
                         {
                             self.previousValue = 0;
                             
                             CGRect frame = self.buttonImage.frame;
                             frame.origin.x = 0;
                             frame.origin.y = 1;
                             frame.size.height = self.frame.size.height - 2.6;
                             self.buttonImage.frame = frame;
                             
                             frame = self.backImage1.frame;
                             frame.origin.x = 0;
                             frame.size.width = self.frame.size.width;
                             frame.size.height = self.frame.size.height - 2.6;
                             self.backImage1.frame = frame;
                         }
                     }
                     completion:^(BOOL finished){
                         if(self.previousValue >= 1.0f)//在最右边显示；“按钮”为黑图，右边图片为黑图，左边为空图
                         {
                             self.buttonImage.image = [UIImage inputSlider:self.buttonImage.frame];
                             
                             self.backImage1.frame = CGRectMake(self.aFrame.size.width, 0.6, 0, self.frame.size.height-2.6);
                             self.backImage1.image = [UIImage imageNamed:@"volumeCell1.png"];
                             self.backImage2.image = [UIImage imageNamed:@"clearBack.png"];
                             
                             self.textView.placeHolder = NSLocalizedString(@"snapPattern", nil);
                             self.snapText = YES;//阅后即焚模式
                             
                             [[NSNotificationCenter defaultCenter]postNotificationName:kSendSnapTextNotification object:[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"isSnapText", nil]];
                         }
                         else   //在最左边显示；“按钮”为灰图，右边图片为空图，左边为灰图
                         {
                             self.buttonImage.image = [UIImage inputSlider:self.buttonImage.frame];
                             
                             self.backImage2.frame = CGRectMake(0, 1, 0, self.frame.size.height-2.6);
                             self.backImage1.image = [UIImage imageNamed:@"clearBack.png"];
                             self.backImage2.image = [UIImage imageNamed:@"volumeCell2.png"];
                             
                             self.textView.placeHolder = NSLocalizedString(@"normalPattern", nil);
                             self.snapText = NO;//普通模式
                             
                             [[NSNotificationCenter defaultCenter]postNotificationName:kSendSnapTextNotification object:[NSDictionary dictionaryWithObjectsAndKeys:@"0",@"isSnapText", nil]];
                         }
                     }
     ];
}

#pragma mark - Message input view
- (void)adjustTextViewHeightBy:(CGFloat)changeInHeight
{
    CGRect prevFrame = self.textView.frame;
    
    int numLines = MAX([self.textView numberOfLinesOfText],
                       [self.textView.text numberOfLines]);

    self.textView.frame = CGRectMake(prevFrame.origin.x,
                                     prevFrame.origin.y,
                                     prevFrame.size.width,
                                     prevFrame.size.height + changeInHeight);
    
    self.textView.contentInset = UIEdgeInsetsMake((numLines >= 6 ? 4.0f : 0.0f),
                                                  0.0f,
                                                  (numLines >= 6 ? 4.0f : 0.0f),
                                                  0.0f);
    self.textView.scrollEnabled = (numLines >= 2);
    
    if(numLines >= 2) {
        CGPoint bottomOffset = CGPointMake(0.0f, self.textView.contentSize.height - self.textView.bounds.size.height);
        [self.textView setContentOffset:bottomOffset animated:YES];
    }
}

+ (CGFloat)textViewLineHeight
{
    return 36.0f; // for fontSize 16.0f
}

+ (CGFloat)maxLines
{
    return 1.0f;
}

+ (CGFloat)maxHeight
{
    return ([JSMessageInputView maxLines] + 2.0f) * 28;
//    return ([JSMessageInputView maxLines] + 2.0f) * 36;
}

@end